package com.lzh.ucenter.controller;


import com.lzh.base.handle.MyException;
import com.lzh.commonutils.CommonResult;
import com.lzh.commonutils.JwtUtils;
import com.lzh.ucenter.entity.Member;
import com.lzh.ucenter.service.MemberService;
import com.lzh.ucenter.vo.LoginVo;
import com.lzh.ucenter.vo.RegisterVo;
import com.lzh.ucenter.vo.UserInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author lizuhu
 * @since 2021-05-19
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class MemberController {
    @Autowired
    private MemberService memberService;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginVo login) {
        String token = memberService.login(login);
        return CommonResult.ok().data("token",token);
    }

    @ApiOperation(value = "注册用户")
    @PostMapping("/regist")
    public CommonResult register(@RequestBody RegisterVo register) {
        boolean result = memberService.register(register);
        if (result) {
            return CommonResult.ok().message("用户注册成功");
        } else {
            return CommonResult.error().message("用户注册失败");
        }
    }

    @ApiOperation(value = "根据token获取登录信息")
    @GetMapping("/getUser")
    public CommonResult getUserByToken(HttpServletRequest request) {

        try {
            String userId = JwtUtils.getUserIdByToken(request);
            UserInfo user = memberService.getUserInfo(userId);
            return CommonResult.ok().data("user",user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(400,"错误");
        }
    }

    @ApiOperation(value = "根据用户id获取用户信息")
    @GetMapping("/getUserById")
    public com.lzh.commonutils.UserInfo getUserById(@RequestParam String userId) {
        Member member = memberService.getById(userId);
        com.lzh.commonutils.UserInfo userInfo = new com.lzh.commonutils.UserInfo();
        BeanUtils.copyProperties(member,userInfo);
        return userInfo;
    }

    @ApiOperation(value = "修改用户信息")
    @PutMapping("/updateUserInfo")
    public CommonResult updateUserInfo(@RequestBody Member member, @RequestParam String userId) {
        member.setId(userId);
        memberService.updateById(member);
        return CommonResult.ok();
    }

}

